#include <iostream>
#include <vector>
#include <cstring>
#include <cstdio>
#include <queue>
#include <algorithm>
using namespace std;
const int N=4*1e4+10;
int n,m;
int depth[N];
int fa[N][16];
vector<int> edge[N];
void bfs(int root)
{
	memset(depth,0x3f3f3f,sizeof(depth));
	queue<int> q;
	depth[root]=1;
	depth[0]=0;
	q.push(root);
	while(q.size())
	{
		int t=q.front();
		q.pop();
		for(int& e:edge[t])
		{
			if(depth[e]>depth[t]+1)
			{
				depth[e]=depth[t]+1;
				q.push(e);
				fa[e][0]=t;
				for(int i=1;i<=15;i++)
				{
					fa[e][i]=fa[fa[e][i-1]][i-1];
				}
			}
		}
	}
}
int lca(int x,int y)
{
	if(depth[x]<depth[y])
		swap(x,y);
	for(int i=15;i>=0;i--)
	{
		if(depth[fa[x][i]]>=depth[y])
			x=fa[x][i];
	}
	if(x==y)
		return y;
		
	for(int i=15;i>=0;i--)
	{
		if(fa[x][i]!=fa[y][i])
		{
			x=fa[x][i];
			y=fa[y][i];
		}
	}
	return fa[x][0];
}


int main()
{
	int root=0;
	cin>>n;
	for(int i=0;i<n;i++)
	{
		int x,y;
		scanf("%d%d",&x,&y);
		if(y==-1)
			root=x;
		else
		{
			edge[x].push_back(y);
			edge[y].push_back(x);
		}
	}
	bfs(root);
	cin>>m;
	while(m--)
	{
		int x,y;
		scanf("%d%d",&x,&y);
		int p=lca(x,y);
		if(p==x)
			cout<<"1"<<endl;
		else if(p==y)
			cout<<"2"<<endl;
		else
			cout<<"0"<<endl;
	}
	return 0;
}
